package com.shigen.demo.ForkJoinDemo;

/**
 * 归并排序
 *
 * @author shigenfu
 * @date 2024/4/8 16:16
 */
public class MergeSortDemo {

    // 归并排序
    static void mergeSort(int[] arr, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            // 简直直接mid
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    private static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    private static void merge(int[] arr, int left, int mid, int right) {
        // 构建一个临时数组暂存arr[left, right]之间有序的元素
        int[] temp = new int[right - left + 1];
        int i = left, j = mid + 1, k = 0;

        // while的临界条件需注意，此时分段有序数组合并
        // [1,2,3] + [1,3,4,5,6] mid = 4
        while (i <= mid && j <= right) {
            if (arr[i] < arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }
        // 剩下的元素直接追加即可，两个while只会走一个
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= right) {
            temp[k++] = arr[j++];
        }

        // 将temp[] => arr[left, right]
        for (i = 0; i < temp.length; i++) {
            arr[left + i] = temp[i];
        }
    }


    public static void main(String[] args) {
        int[] arr = {1, 432, 1, 3243, 54, 32, -10, 43, 90};
        mergeSort(arr, 0, arr.length - 1);
        print(arr);
    }

}
